package com.example.cheapshark.mobile;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;

public class TopDealsPagerActivity extends FragmentActivity {
	private static final int NUMBER_OF_PAGES = CSMobileApplication
			.getNumberOfPages();

	private ViewPager mViewPager;
	private TopDealsFragmentPagerAdapter mMyFragmentPagerAdapter;

	// The circular paging basically came from
	// http://stackoverflow.com/questions/11465815/how-to-create-circular-viewpager
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_top_deals_pager);
		mViewPager = (ViewPager) findViewById(R.id.topDeals);
		mMyFragmentPagerAdapter = new TopDealsFragmentPagerAdapter(
				getSupportFragmentManager(), mViewPager);
		mViewPager.setAdapter(mMyFragmentPagerAdapter);
		mViewPager.setCurrentItem(1);
	}

	private static class TopDealsFragmentPagerAdapter extends
			FragmentPagerAdapter {

		private int pageIDs[];

		public TopDealsFragmentPagerAdapter(FragmentManager fm,
				final ViewPager pager) {
			super(fm);
			pageIDs = new int[getCount()];
			for (int i = 1; i <= NUMBER_OF_PAGES; i++) {
				pageIDs[i] = i - 1;
			}
			pageIDs[0] = pageIDs[NUMBER_OF_PAGES - 1];
			pageIDs[getCount() - 1] = 0;
			pager.setOnPageChangeListener(new OnPageChangeListener() {

				public void onPageSelected(int position) {
					int pageCount = getCount();
					if (position == 0) {
						pager.setCurrentItem(pageCount - 2, false);
					} else if (position == pageCount - 1) {
						pager.setCurrentItem(1, false);
					}
				}

				public void onPageScrolled(int position, float positionOffset,
						int positionOffsetPixels) {
					// TODO Auto-generated method stub
				}

				public void onPageScrollStateChanged(int state) {
					// TODO Auto-generated method stub
				}
			});

		}

		@Override
		public Fragment getItem(int index) {
			return TopDealsFragment.newInstance(pageIDs[index]);
		}

		@Override
		public int getCount() {

			return NUMBER_OF_PAGES + 2;
		}

		public void destroyItem(View container, int position, Object object) {

		}

	}

}
